package com.example.spring_config.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.spring_config.mapper.User;
import com.example.spring_config.dao.UserDao;
import com.example.spring_config.mapper.UserRole;
import com.example.spring_config.service.RoleService;
import com.example.spring_config.service.UserRoleRelationService;
import com.example.spring_config.service.UserService;
import org.assertj.core.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserRoleRelationService userRoleRelationService;
    @Autowired
    private RoleService roleService;

    /**
     * 获取用户列表
     * @return
     */
    @Override
    public List<User> getUserList() {
        return userDao.getUserList();
    }

    /**
     * 修改用户
     * @param user
     * @param roleList
     * @return
     */
    @Override
    public Boolean updateUser(User user, String roleList) {
        //修改用户基本信息
        QueryWrapper<User> q = new QueryWrapper<>();
        q.eq("id",user.getId());
        boolean update = update(user,q);
        boolean flag = true;
        // 给用户赋予权限
        //删除用户原有权限
        userRoleRelationService.remove(new QueryWrapper<UserRole>().eq("u_id",user.getId()));
        if(!(roleList==null || roleList.length()==0)){
            String[] split = roleList.split(",");
            List<Object> objects =  Arrays.asList(split);
            List<UserRole> array = new ArrayList<>();
            for (Object object : objects) {
                UserRole userRole = new UserRole();
                userRole.setUId(user.getId());
                userRole.setRId((String) object);
                array.add(userRole);
            }
            // 插入权限
            flag = userRoleRelationService.saveBatch(array);
        }

        return update&flag;
    }

    /**
     * 获取用户的所有角色
     * @param users
     * @return
     */
    @Override
    public List<User> getUserRole(List<User> users) {
        users.forEach(user -> {
            List<String> roleNameByUid = roleService.getRoleNameByUid(user.getId());
            String str = "";
            for (int i = 0; i < roleNameByUid.size(); i++) {
                if(i==roleNameByUid.size()-1){
                    str+=roleNameByUid.get(i);
                }else {
                    str+=roleNameByUid.get(i)+",";
                }
            }
            user.setRoleStr(str);
        });
        return users;
    }
}
